package com.x.erp.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.tobato.fastdfs.FdfsClientConstants;
import com.x.erp.dao.CarDao;
import com.x.erp.dao.CarImageDao;
import com.x.erp.dao.MarketDao;
import com.x.erp.dao.ModelMappingQczjDao;
import com.x.erp.dao.ShopMappingQczjDao;
import com.x.erp.model.Car;
import com.x.erp.model.CarImage;
import com.x.erp.model.Market;
import com.x.erp.thirdparty.CarMappingQczj;
import com.x.erp.thirdparty.HomeCarInfo;
import com.x.erp.thirdparty.ModelMappingQczj;
import com.x.erp.thirdparty.SalesPerson;
import com.x.erp.thirdparty.ShopMappingQczj;
import com.x.erp.util.QczjApi;
import com.x.erp.util.QczjResult;
import com.x.framework.service.BaseService;

@Component
public class QczjService extends BaseService {

	private Logger logger = LoggerFactory.getLogger(QczjService.class);
	
	@Autowired
	private ShopMappingQczjDao shopMappingQczjDao;

	@Autowired
	private ModelMappingQczjDao modelMappingQczjDao;

	@Autowired
	private CarMappingQczjService carMappingQczjService;

	@Autowired
	private CarImageDao carImageDao;

	@Autowired
	private QczjApi qczjApi;
	
	@Autowired
	private MarketDao marketDao;
	
	@Autowired
	private CarDao carDao;
	
	// 发布车源
	public void insertCarQczj(Car car) {
		
		if(car != null && StringUtils.isNotEmpty(car.getCarId())) {
			try {
				Car selectCar = new Car();
				selectCar.setCarId(car.getCarId());
				car = carDao.selectCar(selectCar);
				if(car == null){
					logger.info("获取车辆信息失败！");
					return;
				}
			} catch (Exception e) {
				logger.info("获取车辆信息失败！" + e);
				return;
			}
			// 获取商家id和商家唯一标识key
			ShopMappingQczj shopMappingQczj = getDealeridAndKey(car);
			if(shopMappingQczj == null){
				logger.info("获取汽车之家商家id和商家唯一标识key失败！carId = " + car.getCarId());
				return;
			}
			Integer dealerid = shopMappingQczj.getMappingDealerId();
			String key = shopMappingQczj.getMappingDealerKey();
			
			// 判断是否为第一次发布车源
			CarMappingQczj carMappingQczj = new CarMappingQczj();
			carMappingQczj.setCarId(car.getCarId());
			List<CarMappingQczj> selectQczjShopList = carMappingQczjService.selectQczjShopList(carMappingQczj);
			if(!selectQczjShopList.isEmpty()){
				try {
					QczjResult setCarRepublish = qczjApi.setCarRepublish(dealerid, key, selectQczjShopList.get(0).getMappingCarId());
					if (setCarRepublish.getReturncode() != 0) {
						logger.info("重新发布车源失败，提示码：" + setCarRepublish.getReturncode() + "  ，提示信息：" + new String(setCarRepublish.getMessage().getBytes(),"UTF-8"));
						return;
					}
				} catch (Exception e) {
					logger.info("重新发布车源失败！" + e);
					return;
				}
			}else{
				//上传图片
				String carvin = null;
				String driverlicenseimage = null;
				StringBuffer images = new StringBuffer();
				try {
					CarImage carImg = new CarImage();
					carImg.setCarId(car.getCarId());
					List<CarImage> carImages = carImageDao.selectCarImageByCarId(carImg);
					if(carImages.isEmpty()){
						logger.info("图片查询失败！");
						return;
					}
					for (CarImage carImage : carImages) {
					    QczjResult uploadImage = qczjApi.uploadImage(dealerid, key, FdfsClientConstants.CLIENT_REQUEST_URL + carImage.getImageUrl(), carImage.getImageSeq());
					    if (uploadImage.getReturncode() != 0) {
					    	logger.info("上传图片失败，提示码：" + uploadImage.getReturncode() + "  ，提示信息：" + new String(uploadImage.getMessage().getBytes(),"UTF-8"));
					    	return;
						}
						String result = uploadImage.getResult();
						JSONObject obj = JSONObject.parseObject(result);
						String qczjImgUrl = obj.get("img").toString();
						if (carImage.getImageKey().equals("vehicle_license")) {
							carvin = car.getCarVin();
							driverlicenseimage = qczjImgUrl;
						} else {
							images.append(qczjImgUrl).append(",");
							images.substring(0, images.length()-1);
						}
					}
				} catch (Exception e) {
					logger.info("获取图片失败！" + e);
					return;
				}
					
				// 获取车型库关系
				Integer productId = null;
				Integer seriesId = null;
				Integer brandId = null;;
				try {
					ModelMappingQczj modelMappingQczj = new ModelMappingQczj();
					modelMappingQczj.setModelId(car.getModelId());
					List<ModelMappingQczj> selectQczjModelList = modelMappingQczjDao.selectQczjModelList(modelMappingQczj);
					if(selectQczjModelList.isEmpty()){
						logger.info("获取车型库关系失败！");
						return;
					}
					productId = selectQczjModelList.get(0).getMappingProductId();
					seriesId = selectQczjModelList.get(0).getMappingSeriesId();
					brandId = selectQczjModelList.get(0).getMappingBrandId();
				} catch (Exception e) {
					logger.info("获取车型库关系失败！" + e);
					return;
				}
	
				// 获取颜色
				int colorid = qczjApi.getColorId(car.getCarOutColor());
				
				// 获取省市
				String provinceId = null;
				String cityId = null;
				try {
					Market market = new Market();
					market.setMarketId(car.getMarketId());
					List<Market> selectMarketList = marketDao.selectMarketList(market);
					if(selectMarketList.isEmpty()){
						logger.info("获取省市失败！");
						return;
					}
					provinceId = selectMarketList.get(0).getProvinceId();
					cityId = selectMarketList.get(0).getCityId();
				} catch (Exception e) {
					logger.info("获取省市失败！" + e);
					return;
				}
				
				// 获取销售代表
				SalesPerson salesperson = null;
				try {
					QczjResult sales = qczjApi.getSales(dealerid, key);
					if (sales.getReturncode() != 0) {
						logger.info("获取销售代表失败，提示码：" + sales.getReturncode() + "  ，提示信息：" + new String(sales.getMessage().getBytes(),"UTF-8"));
						return;
					}
					JSONObject obj = JSONObject.parseObject(sales.getResult());
					JSONArray arr = obj.getJSONArray("saleslist");
					for (int i = 0; i < arr.size(); i++) {
						salesperson = arr.getObject(0, SalesPerson.class);
					}
				}catch (Exception e) {
					logger.info("获取销售代表失败！" + e);
					return;
				}
				
				// 发布车源（首先判断是否为第一次发布车源）
				try {
					HomeCarInfo homeCarInfo = new HomeCarInfo(car, images.toString(), driverlicenseimage, carvin, salesperson, productId, seriesId, brandId, colorid, provinceId, cityId);
					QczjResult insertCar = qczjApi.insertCar(dealerid, key, homeCarInfo);
					if (insertCar.getReturncode() != 0) {
						logger.info("发布车源失败，提示码：" + insertCar.getReturncode() + "  ，提示信息：" + new String(insertCar.getMessage().getBytes(),"UTF-8"));
						return;
					}
					String result = insertCar.getResult();
					JSONObject carResult = JSONObject.parseObject(result);
					int mappingCarId = carResult.getIntValue("carid");
					// 将carId和汽车之家mappingCarId存起来
					carMappingQczj.setMappingCarId(mappingCarId);
					carMappingQczjService.insertQczjCar(carMappingQczj);
				} catch (Exception e) {
					logger.info("添加车辆失败！" + e);
					return;
				}
			}
		}
	}
	
	// 车源下架
	public void updateCarSaleState30(Car car) {
		if(car != null){
			try {
				// 获取商家id和商家唯一标识key
				ShopMappingQczj shopMappingQczj = getDealeridAndKey(car);
				if(shopMappingQczj == null){
					logger.info("获取汽车之家商家id和商家唯一标识key失败！carId = " + car.getCarId());
					return;
				}
				Integer dealerid = shopMappingQczj.getMappingDealerId();
				String key = shopMappingQczj.getMappingDealerKey();
				CarMappingQczj carMappingQczj = new CarMappingQczj();
				carMappingQczj.setCarId(car.getCarId());
				List<CarMappingQczj> selectQczjShopList = carMappingQczjService.selectQczjShopList(carMappingQczj);
				if(!selectQczjShopList.isEmpty()){
					QczjResult setCarInvalid = qczjApi.setCarInvalid(dealerid, key, selectQczjShopList.get(0).getMappingCarId());
					if (setCarInvalid.getReturncode() != 0) {
						logger.info("车源下架失败，提示码：" + setCarInvalid.getReturncode() + "  ，提示信息：" + new String(setCarInvalid.getMessage().getBytes(),"UTF-8"));
						return;
					}
				}
				
			} catch (Exception e) {
				logger.info("汽车之家车源下架失败！" + e);
				return;
 			}
		}
	}
	
	// 车源出库(设为已售)
	public void updateCarStockState40(Car car) {
		if(car != null && StringUtils.isNotEmpty(car.getCarId())) {
			try {
				Car selectCar = new Car();
				selectCar.setCarId(car.getCarId());
				// 获取车辆信息
				car = carDao.selectCar(selectCar);
				if(car == null){
					logger.info("获取车辆信息失败！");
					return;
				}
				// 获取商家id和商家唯一标识key
				ShopMappingQczj shopMappingQczj = getDealeridAndKey(car);
				if(shopMappingQczj == null){
					logger.info("获取汽车之家商家id和商家唯一标识key失败！carId = " + car.getCarId());
					return;
				}
				Integer dealerid = shopMappingQczj.getMappingDealerId();
				String key = shopMappingQczj.getMappingDealerKey();

				CarMappingQczj carMappingQczj = new CarMappingQczj();
				carMappingQczj.setCarId(car.getCarId());
				List<CarMappingQczj> selectQczjShopList = carMappingQczjService.selectQczjShopList(carMappingQczj);
				if(!selectQczjShopList.isEmpty()){
					QczjResult setSaled = qczjApi.setSaledCar(dealerid, key, selectQczjShopList.get(0).getMappingCarId(),
							car.getCarRetailPrice());
					if (setSaled.getReturncode() != 0) {
						logger.info("车源设为已售失败，提示码：" + setSaled.getReturncode() + "  ，提示信息：" + new String(setSaled.getMessage().getBytes(),"UTF-8"));
						return;
					}
				}
			} catch (Exception e) {
				logger.info("汽车之家车源设为已售失败！" + e);
				return;
			}
		}
	}
	
	// 获取商家id和商家唯一标识key
	public ShopMappingQczj getDealeridAndKey(Car car){
		try {
			ShopMappingQczj shopMappingQczj = new ShopMappingQczj();
			shopMappingQczj.setShopId(car.getShopId());
			List<ShopMappingQczj> selectShopMappingQczjList = shopMappingQczjDao.selectQczjShopList(shopMappingQczj);
			if(!selectShopMappingQczjList.isEmpty()){
				return selectShopMappingQczjList.get(0);
			}
			return null;
		} catch (Exception e) {
			logger.info("获取商家id和key失败！" + e);
			return null;
		}
	}
}
